package com.reny.ll.git.mvvm

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.vlayout.DelegateAdapter
import com.ethanhua.skeleton.RecyclerViewSkeletonScreen
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.reny.ll.git.core.BaseDelegate
import com.reny.ll.git.core.RBaseActivity
import com.reny.ll.git.mvvm.extras.observe
import com.reny.ll.git.mvvm.extras.setStatusHeight
import com.reny.ll.git.mvvm.state.*
import com.reny.ll.git.mvvm.view.IStateView
import com.reny.ll.git.mvvm.view.MultiStateView
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.layout.api.RefreshLayout

open class MvvmDelegateImp(private val master: Any) : BaseDelegate {

    var viewModel: BaseViewModel? = null

    protected var mScreenBuilder : ViewSkeletonScreen.Builder? = null
    private val mAllScreenBuilders = HashSet<ViewSkeletonScreen.Builder>()
    private val mAllScreens = HashSet<ViewSkeletonScreen>()

    protected var mScreenRecyclerBuilder: RecyclerViewSkeletonScreen.Builder? = null
    private val mAllScreenRecyclerBuilders = HashSet<RecyclerViewSkeletonScreen.Builder>()
    private val mAllScreenRecyclers = HashSet<RecyclerViewSkeletonScreen>()

    var mMsv: MultiStateView? = null
    private var mRefreshLayout: RefreshLayout? = null

    private val spaceAdapter: SpaceAdapter by lazy {
        SpaceAdapter((master as MvvmView).getNoMoreTip())
    }

    private fun getNotifySpaceAdapter(): SpaceAdapter {
        spaceAdapter.noMoreTip = getNoMoreTip()
        spaceAdapter.notifyDataSetChanged()
        return spaceAdapter
    }

    private fun getNoMoreTip(): String = if(master is MvvmView) master.getNoMoreTip() ?: "" else ""//No More Data

    fun getStateView(@LoadState state: Int): IStateView? {
        return mMsv?.getStateView(state)
    }

    private fun getRootView(): View? = (master as MvvmView).rootView()

    open fun initCommonView() {
        initStatusView()
        initToolBar()
        initMultiStateView()
        addScreenBuilders()
        initRefreshLayout()
        //initAutoScroll()
    }


    override fun onCreate(owner: LifecycleOwner?) {
        if(master is LifecycleOwner && master is MvvmView){
            viewModel = master.viewModel

            viewModel?.let {vm ->
                master.observe(vm.loadState){
                    showPageState(it)
                }
                master.observe(vm.refreshState){
                    showRefresh(it)
                }
            }

        }

        if(master is Activity && master is MvvmView){
            master.initCommonView()
        }
    }

    override fun onStart(owner: LifecycleOwner?) {}

    override fun onResume(owner: LifecycleOwner?) {}

    override fun onPause(owner: LifecycleOwner?) {}

    override fun onStop(owner: LifecycleOwner?) {}

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        if(master is Fragment && master is MvvmView){
            master.initCommonView()
        }
    }

    override fun onDestroyView() {}

    override fun onTrimMemory(level: Int) {}

    override fun onLowMemory() {}

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {}

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}

    override fun onDestroy(owner: LifecycleOwner?) {
        if(master is RBaseActivity<*>) {
            master.binding?.unbind()
        }
    }


    private fun initStatusView() {
        val status: View? = getRootView()?.findViewById(R.id.status)
        status?.let {
            setStatusHeight(it)
        }
    }

    private fun initToolBar() {
        if(master is AppCompatActivity) {
            val tool: Toolbar? = getRootView()?.findViewById(R.id.tool)
            tool?.let {
                it.title = ""
                master.setSupportActionBar(it)
                //给左上角图标的左边加上一个返回的图标
                master.supportActionBar?.setDisplayHomeAsUpEnabled(true)
                it.setNavigationOnClickListener { master.onBackPressed() }
            }
        }
    }

    private fun initMultiStateView() {
        val view: View? = getRootView()?.findViewById(R.id.msv)
        view?.let {
            mMsv = MultiStateView(it)
        }
    }

    private fun addScreenBuilders() {
        getScreenBuilders()?.forEach {
            mAllScreenBuilders.add(it)
        }
        getScreenRecyclerBuilders()?.forEach {
            mAllScreenRecyclerBuilders.add(it)
        }
    }

    /*private fun initAutoScroll() {
        getRootView()?.findViewById<AutoScrollBackLayout>(R.id.scroll_layout)?.bindScrollBack()
    }*/

    //多个ViewSkeletonScreen.Builder 重写
    open fun getScreenBuilders():MutableList<ViewSkeletonScreen.Builder>?{
        mScreenBuilder?.let {
            return mutableListOf(it)
        }
        return null
    }

    //多个RecyclerViewSkeletonScreen.Builder 重写
    open fun getScreenRecyclerBuilders():MutableList<RecyclerViewSkeletonScreen.Builder>?{
        mScreenRecyclerBuilder?.let {
            return mutableListOf(it)
        }
        return null
    }

    private fun resetRefreshLayout(){
        val view: View? = getRootView()?.findViewById(R.id.srl)
        view?.let {
            if (view is RefreshLayout) {
                mRefreshLayout = view
            }
        }
    }

    //如果有刷新控件 需要提前初始化好 和上面getViewReplacer()不太一样
    open fun initRefreshLayout(){
        if(mRefreshLayout == null) {
            resetRefreshLayout()

            //init
            mRefreshLayout?.apply {
                setEnableOverScrollDrag(true)
                setEnableAutoLoadMore(true)
                setEnableHeaderTranslationContent(true) //内容跟随下拉
                setEnableLoadMoreWhenContentNotFull(true) //是否在列表不满一页时候开启上拉加载功能
                //setEnableFooterFollowWhenLoadFinished(getRootAdapter() == null) //设置是否在没有更多数据之后 Footer 跟随内容
                setEnableFooterFollowWhenNoMoreData(getRootAdapter() == null) //设置是否在没有更多数据之后 Footer 跟随内容

                setOnRefreshListener {
                    refreshData(true)
                }
                setOnLoadMoreListener {
                    refreshData(false)
                }
            }
        }
    }

    private fun getRootAdapter(): DelegateAdapter? {
        val rv: View? = getRootView()?.findViewById(R.id.rv)
        if(rv != null && rv is RecyclerView) {
            rv.adapter?.let {
                if (it is DelegateAdapter) {
                    return it
                }
            }
        }
        return null
    }


    private fun showPageState(@LoadState state: Int) {
        when(state){
            STATE_LOADING -> {
                //如果Loading为骨架屏
                if(mAllScreenBuilders.size > 0 || mAllScreenRecyclerBuilders.size > 0){
                    mMsv?.showContent()
                    if(mAllScreenBuilders.size > 0) {
                        mAllScreens.clear()
                        mAllScreenBuilders.forEach {
                            mAllScreens.add(it.show())
                        }
                    }
                    if(mAllScreenRecyclerBuilders.size > 0){
                        mAllScreenRecyclers.clear()
                        mAllScreenRecyclerBuilders.forEach {
                            mAllScreenRecyclers.add(it.show())
                        }
                    }
                } else {
                    //如果Loading为一个普通布局文件
                    useViewReplacer(state)
                }
            }
            STATE_CONTENT -> {
                if(mAllScreens.size > 0){
                    mAllScreens.forEach {
                        it.hide()
                    }
                }
                if(mAllScreenRecyclers.size > 0){
                    mAllScreenRecyclers.forEach {
                        it.hide()
                    }
                }
                useViewReplacer(state)
            }
            else -> {
                //加载出错，网络出错，数据为空等页面 依然采用普通布局文件
                useViewReplacer(state)
            }

        }
    }

    private fun useViewReplacer(@LoadState state: Int){
        mMsv?.showState(state)
        val emptyRetry = if(master is MvvmView) master.emptyRetry else true
        mMsv?.setOnClick(if(state == STATE_LOADING || state == STATE_CONTENT || (state == STATE_EMPTY && !emptyRetry)) null else View.OnClickListener {
            refreshData(true)
        })
    }

    private fun refreshData(refresh:Boolean){
        viewModel?.loadData(refresh)
    }

    private fun showRefresh(state: RefreshState, enableLoadMore:Boolean = viewModel?.enableLoadMore ?: true) {
        if(mRefreshLayout != null){
            getRootAdapter()?.removeAdapter(spaceAdapter)
            mRefreshLayout?.apply {
                setEnableLoadMore(enableLoadMore)
                //isEnableLoadMore = enableLoadMore
                setNoMoreData(false)
                finishRefresh()

                if (state.noMore) {
                    ClassicsFooter.REFRESH_FOOTER_NOTHING = getNoMoreTip()
                    finishLoadMoreWithNoMoreData()

                    if(!enableLoadMore){
                        setEnableLoadMore(false)
                        //isEnableLoadMore = false
                    }
                    getRootAdapter()?.addAdapter(getNotifySpaceAdapter())
                } else {
                    finishLoadMore()
                }
            }
        }
    }


}